<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import echarts from '@/utils/echarts'
import { sceneryPieChartService, hotelPieChartService } from '@/apis/home'

const props = defineProps({
  type: {
    type: String,
    required: true
  }
})

// 存储饼图数据
const PieChartData = ref([])

// 获取柱形图数据
const getPieChart = async () => {
  let res = []
  switch (props.type) {
    case '景点':
      res = await sceneryPieChartService()
      break
    case '酒店':
      res = await hotelPieChartService()
      break
  }
  PieChartData.value = res.data
}

// 获取图表容器
const chartContainerRef = ref(null)

// 声明一个用于保存echarts实例
let chartInstance = null

onMounted(async () => {
  await getPieChart()

  if (PieChartData.value.length > 0) {
    // 初始化图表
    chartInstance = echarts.init(chartContainerRef.value)

    // 定义图表的配置项和数据
    const option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '5%',
        left: 'center'
      },
      series: [
        {
          name: props.type === '景点' ? '景点等级' : '酒店星级',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 40,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: PieChartData.value.map((item) => {
            return {
              value: item.count,
              name: item.type
            }
          })
        }
      ]
    }

    // 使用配置项和数据显示表格
    chartInstance.setOption(option)

    // 监听窗口大小变化，自动调整图表大小
    window.addEventListener('resize', () => {
      chartInstance.resize()
    })
  }
})

// 在组件卸载时清理资源
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    window.removeEventListener('resize', chartInstance.resize)
  }
})
</script>

<template>
  <div ref="chartContainerRef" class="chart"></div>
</template>

<style lang="scss" scoped>
.chart {
  width: auto;
  height: 400px;
}
</style>
